package org.itboys.mobile.controller.weixin;

import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.service.lasted.SystemDictionaryService;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mobile.dto.SundayMemberSessionDto;
import org.itboys.mobile.dto.product.SundayProductBrandDto;
import org.itboys.mobile.dto.product.SundayProductCategoryDto;
import org.itboys.mobile.dto.product.SundayProductDto;
import org.itboys.mobile.service.mongo.front.SundayFrontFootprintService;
import org.itboys.mobile.service.mysql.front.SundayFrontProductBrandService;
import org.itboys.mobile.service.mysql.front.SundayFrontProductCategoryService;
import org.itboys.mobile.service.mysql.front.SundayFrontProductService;
import org.itboys.mobile.service.mysql.web.product.SundayProductBrandService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangyang on 2018/1/4.
 * 圣代_商品_controller_weixin
 */
@Controller
@RequestMapping("/sunday/weixin/product")
public class SundayWeiXinProductController extends BaseController {

    @Autowired
    private SundayFrontProductCategoryService productCategoryService;
    @Autowired
    private SundayFrontProductService productService;
    @Autowired
    private SundayFrontFootprintService footprintService;
    @Autowired
    private SundayFrontProductBrandService brandService;
    @Autowired
    private SystemDictionaryService dictionaryService;

    /**
     * 分页树形页
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/category/index", method = {RequestMethod.GET, RequestMethod.POST})
    public String category_index(
            HttpServletRequest request, Model model) {
        try{
            SundayMemberSessionDto memberSessionDto = AccountIdHoldUtils.getSessionMember(request);
            List<SundayProductCategoryDto> categories = productCategoryService.getTree(memberSessionDto.getId(), 0l);
            model.addAttribute("categories", categories);
            return "/aigou/weixin/product/category/index";
        }catch (Exception e){
            logger.error("/sunday/weixin/product/category/index----e="+e.getMessage());
            e.printStackTrace();
            return "/aigou/weixin/error";
        }
    }

    /**
     * 分页-商品页
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/category/index2", method = {RequestMethod.GET, RequestMethod.POST})
    public String category_index2(
            @ApiParam(required = false, name = "firstCatId", value = "一级分类ID") @RequestParam(value = "firstCatId", required = false) Long firstCatId,
            HttpServletRequest request,Model model) {
        try{
            AccountIdHoldUtils.getSessionMember(request);
            List<SundayProductCategoryDto> categories = productCategoryService.getChildren(firstCatId);
            model.addAttribute("categories", categories);
            model.addAttribute("firstCatId",firstCatId);
            //2018年2月6日，返回logo
            model.addAttribute("index_image_logo",dictionaryService.getImageByValue("index_image_logo"));
            return "/aigou/weixin/product/category/index2";
        }catch (Exception e){
            logger.error("/sunday/weixin/product/category/index2----e="+e.getMessage());
            e.printStackTrace();
            return "/aigou/weixin/error";
        }
    }
    /**
     * 获取品牌
     * @param request
     * @param response
     */
    @RequestMapping(value = "/brand/getData", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "【微信端】获取品牌列表。不分页")
    public void brand_getData(
            HttpServletRequest request,
            HttpServletResponse response,
            Model model,
            @ApiParam(required = false, name = "firstCatId", value = "一级分类ID。只在顶部分类时使用") @RequestParam(value = "firstCatId", required = false) Long firstCatId,
            @ApiParam(required = false, name = "secondCatId", value = "二级分类ID。只在顶部分类进入后，选择对应的二级分类ID") @RequestParam(value = "secondCatId", required = false) Long secondCatId,
            @ApiParam(required = false, name = "name", value = "品牌。模糊查询参数") @RequestParam(value = "name", required = false) String name
            ){
        try{

            SundayMemberSessionDto member = AccountIdHoldUtils.getSessionMember(request);
            List<SundayProductBrandDto> brand = brandService.getBrands(firstCatId,secondCatId,name,null);
            ResponseMessage.success(brand);
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/weixin/product/brand/getData----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    /**
     * 商品主页，带入查询参数
     *
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = "/index", method = {RequestMethod.GET, RequestMethod.POST})
    public String index(
            HttpServletRequest request,Model model,
            @RequestParam(value = "firstCatId", required = false) Long firstCatId,
            @RequestParam(value = "secondCatId", required = false) Long secondCatId,
            @RequestParam(value = "brandName", required = false) String brandName,
            @RequestParam(value = "isCat", required = false) Integer isCat
            ) {
        try{
            AccountIdHoldUtils.getSessionMember(request);
            //firstCatId=LongUtil.isNotZreo(firstCatId)?firstCatId:null;
           // secondCatId=LongUtil.isNotZreo(secondCatId)?secondCatId:null;
            brandName=StringUtils.isNotEmpty(brandName)?brandName:"品牌";
            isCat=isCat!=null?isCat:0;
            // List<SundayProductCategoryDto> categories= productCategoryService.getTree(memberSessionDto.getId(),0l);
            model.addAttribute("firstCatId", firstCatId);
            model.addAttribute("secondCatId", secondCatId);
            model.addAttribute("name", request.getParameter("name"));
            model.addAttribute("type", request.getParameter("type"));
            model.addAttribute("brandId", request.getParameter("brandId"));
            model.addAttribute("shopId", request.getParameter("shopId"));
            //2018年2月2日
            model.addAttribute("brandName", brandName);
            model.addAttribute("isCat",isCat);
           if(LongUtil.isNotZreo(firstCatId)&&isCat==1){
              // SundayMemberSessionDto memberSessionDto = AccountIdHoldUtils.getSessionMember(request);
               List<SundayProductCategoryDto> categories = productCategoryService.getChildren(firstCatId);
               model.addAttribute("categories", categories);
           }
            //2018年2月4日，获取所有品牌
          /*  Map<String,Object> param = new HashMap<String,Object>();
            param.put("sort_name","sequence");
            param.put("sort_order","ASC");
            List<SundayProductBrand> brands = brandService.select(param);
            model.addAttribute("brands",brands);*/

            //2018年2月6日，返回logo
            model.addAttribute("index_image_logo",dictionaryService.getImageByValue("index_image_logo"));
            return "/aigou/weixin/product/index";
        }catch (Exception e){
            logger.error("/sunday/weixin/product/index----e="+e.getMessage());
            e.printStackTrace();
            return "/aigou/weixin/error";
        }
    }

    /**
     * 分页查询商品
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getData", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "【微信端】获取商品列表。分页")
    public String getData(
            HttpServletRequest request,
            Model model,
            @ApiParam(required = true, name = "flag", value = "标示是获取哪个页面的商品列表数据:1-首页分类下商品,2-首页海淘数据,3-首页拼团数据,4-首页爱购币数据") @RequestParam(value = "flag", required = true) String flag,
            @ApiParam(required = false, name = "name", value = "商品名称。模糊查询参数") @RequestParam(value = "name", required = false) String name,
            @ApiParam(required = false, name = "brandId", value = "品牌ID。查询参数。注意搭配type参数。目前只有全球购（海淘）中有此参数") @RequestParam(value = "brandId", required = false) Long brandId,
            @ApiParam(required = false, name = "shopId", value = "商家ID。查询参数") @RequestParam(value = "shopId", required = false) Long shopId,
            @ApiParam(required = false, name = "firstCatId", value = "一级分类ID。只在顶部分类时使用") @RequestParam(value = "firstCatId", required = false) Long firstCatId,

            @ApiParam(required = false, name = "secondCatId", value = "二级分类ID。只在顶部分类进入后，选择对应的二级分类ID") @RequestParam(value = "secondCatId", required = false) Long secondCatId,
           // @ApiParam(required = false, name = "type", value = "商品类型。4海淘，5金领，6爱购币，7积分，8秒杀，9拼团，10试用") @RequestParam(value = "type", required = false) Integer type,
            @ApiParam(required = false, name = "type", value = "商品类型。4海淘，5分销，6爱购币，7积分，8秒杀，9拼团，10试用") @RequestParam(value = "type", required = false) Integer type,

            @ApiParam(required = true, name = "pageSize", value = "分页参数。每页数量。默认20") @RequestParam(value = "pageSize", required = true) String pageSize,
            @ApiParam(required = true, name = "pageNumber", value = "分页参数。第几页。默认1") @RequestParam(value = "pageNumber", required = true) String pageNumber,
            @ApiParam(required = false, name = "sort", value = "排序参数。字段名称。默认为空。销量：saleNumber,价格：price") @RequestParam(value = "sort", required = false) String sort,
            @ApiParam(required = false, name = "order", value = "排序参数。默认为空。ASC正序/DESC倒序") @RequestParam(value = "order", required = false) String order) {
        try {
            SundayMemberSessionDto memberSessionDto = AccountIdHoldUtils.getSessionMember(request);
            List<SundayProductDto> products = productService.selectProduct(request, memberSessionDto.getId(),shopId, firstCatId,secondCatId, type,brandId);
            //2018年2月3日，
            model.addAttribute("products", products);
            model.addAttribute("flag",flag);
            return "/aigou/weixin/product/data";

        } catch (Exception e) {
            logger.error("/sunday/mobile/product/select----e=" + e.getMessage());
            e.printStackTrace();
            return "/aigou/weixin/error";
        }

    }
    @RequestMapping(value = "/detail", method ={RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "【微信端】获取商品详情。")
    public String detail(
            HttpServletRequest request,
            Model model,
            @ApiParam(required = true, name = "productId", value = "商品ID") @RequestParam(value = "productId", required = true) Long productId) {
        try{
            SundayMemberSessionDto memberSessionDto = AccountIdHoldUtils.getSessionMember(request);
            SundayProductDto product = productService.getDetail(memberSessionDto.getId(), productId);
            model.addAttribute("product", product);

            //生成足迹
            footprintService.save(memberSessionDto.getId(),productId);
            return "/aigou/weixin/product/detail";
        }catch (Exception e){
            logger.error("/sunday/weixin/product/detail----e="+e.getMessage());
            e.printStackTrace();
            return "/aigou/weixin/error";
        }
    }

}
